﻿module Sail {
    export interface IEvent {
        handle: string;
        act: Function;
    }
    export interface IPaginationSetting {
        isPaging?: boolean;
        bodyContainer?: any;
        getPostKey?: Function;
        pageSize?: number;
        handleName?: any;
        headContainer?: any;
        footContainer?: any;
        ajaxType?: Function;
        bodyTmpl?: any;
        footTmpl?: any;
        queryed?: any;
        titles?: Array<ITHead>;
        events?: Array<IEvent> | Object;
        reQueryHandle?: string;
    }

    export interface IPageSetting {
        first: string;
        last: string;
        next: string;
        pre: string;
    }

    export var pageSetting: IPageSetting = {
        first: "第一页",
        last: "最末页",
        next: ">>",
        pre: "<<"
    };

    export var noDataTmpl: string = "<div class='nodata'></div>";

    $.fn.noData = function (text: string) {
        noData(this, text);
        return $(this);
    }

    export function noData(desc: JQuery, text: string) {
        var tag = desc.tagName();
        desc.empty();
        var $tr: JQuery = null;
        if (tag === "TBODY") {
            var $tr = desc.parents("table").find("thead tr:eq(0)");
            var cols = 0;
            $tr.find("th").each(function (i, o) {
                var cs = $(o).attr("colspan");
                cols += (cs ? parseInt(cs) : 1);
            })
            $tr = $("<tr><td></td></tr>").appendTo(desc);
            desc = $tr.find("td").attr("colspan", cols);
        }
        text = text || noDataTmpl;
        desc.html(noDataTmpl);
    }

    export function setPageSetting(set: IPageSetting) {
        pageSetting = set;
    }

    /**
     * 生成页码
     * @param {any} pageInfo
     * @returns
     */
    function loadPages(pageInfo: any): any {
        pageInfo.Pages = [];
        if (pageInfo.PageIndex > 1) {
            pageInfo.Pages.push({ index: 1, title: pageSetting.first });
            pageInfo.Pages.push({ index: pageInfo.PageIndex - 1, title: pageSetting.pre });
        }
        for (var i = pageInfo.StartIndex; i <= pageInfo.EndIndex; i++) {
            pageInfo.Pages.push({ index: i, title: i, isSelect: i == pageInfo.PageIndex });
        }

        if (pageInfo.PageIndex < pageInfo.PageCount) {
            pageInfo.Pages.push({ index: pageInfo.PageIndex + 1, title: pageSetting.next });
            pageInfo.Pages.push({ index: pageInfo.PageCount, title: pageSetting.last });
        }
        return pageInfo.Pages;
    };


    /**
     * 简化设置容器参数的方法,只要传入外层容器选择器即可
     * @param set
     * @param container
     * @param isTable
     */
    export function SetContainer(set: IPaginationSetting, container: string, isNotTable?: boolean) {
        var data = !isNotTable
            ? {
                reQueryHandle: `${container} .btnQuery"`, //查询按钮
                headContainer: `${container}  table thead`,//头部容器
                bodyContainer: `${container}  table tbody`,
                footContainer: `${container}  .page`,//底部容器 
            }
            :
            {
                reQueryHandle: `${container} .btnQuery"`, //查询按钮
                headContainer: null,//头部容器
                bodyContainer: `${container} .pageBody`,
                footContainer: `${container} .page`,//底部容器 
            };
        return $.extend(data, set);
    }

    //获取当前元素的选择器
    $.fn.getPath = function () {
        var current = $(this);
        var path = new Array();
        var realpath = "BODY";
        while ($(current).prop("tagName") != "BODY") {
            var index = $(current).parent().find($(current).prop("tagName")).index($(current));
            var name = $(current).prop("tagName");
            var selector = " " + name + ":eq(" + index + ") ";
            path.push(selector);
            current = $(current).parent();
        }
        while (path.length != 0) {
            realpath += path.pop();
        }
        return realpath;
    }

    $.fn.SetContainer = function (set: IPaginationSetting, isNotTable?: boolean) {

    }



    export class Pagination {
        constructor(set: IPaginationSetting) {

            var ss = Sail.SetContainer({
                isPaging: true,
                ajaxType: () => "get",
                queryed: null, //查询完成后的回调
                pageSize: 10,//每页行数 
                bodyTmpl: "#listTmpl", //内容模板
                footTmpl: 'tableFoot', //页脚模板
                titles: [], //标题
                handleName: null,//handle             
                events: [],//事件集合
                getPostKey() { return {}; }  //获取提交数据的方法 
            }, "#pageList");

            set = jQuery.extend(

                ss
                , set);
            this.settings = set;

            this.Container = $(set.bodyContainer);
            var result = this;

            if (set.events) {
                $.each(set.events, (index, event) => {
                    if (event.handle && event.act) {
                        this.Container.click(event.handle, function () {
                            event.act($.view(this).data, this, this);
                        });
                    }
                });
            };

            this.currentIndex = 1;

            $(set.reQueryHandle).click(() => {
                this.Query(1);
            });

            if (set.headContainer && set.titles) $(set.headContainer).MakeHead(set.titles);

            $(set.footContainer).unbind().click(".onPage", function () {
                var page: any = $(this).data("page");
                result.Query(page);
            });



        }

        currentIndex: number;
        public Container: JQuery;
        settings: IPaginationSetting;


        ///读取数据
        Query(pageIndex?: number) {
            const tooltip = '[data-toggle="tooltip"]';
            if (pageIndex) this.currentIndex = pageIndex;

            pageIndex = this.currentIndex;
            var settings = this.settings;
            var postData = settings.getPostKey();

            if (settings.isPaging) {
                postData["pageSize"] = settings.pageSize;
                postData["pageIndex"] = pageIndex;
            }

            var url = settings.handleName;
            if (typeof url == "function") url = url();

            var type = settings.ajaxType();

            if (type !== "get") postData = { "": JSON.stringify(postData) };

            $.ajax({
                type: type,
                url: url,
                data: postData,
                dataType: "json",
                success: data => {
                    if (data && data.IsSuccess) {
                        var infoDatas = data.Data;
                        if (settings.isPaging) {
                            loadPages(data.Data.PageInfo);
                            infoDatas = data.Data.Data;
                        }
                        this.Container = $(settings.bodyContainer);
                        this.Container.Link(settings.bodyTmpl, infoDatas);

                        if (data.Data.Data.length === 0) {
                            noData(this.Container, "");
                        }

                        this.Container.TableChange();

                        if (settings.isPaging && settings.footTmpl && settings.footContainer)
                            $(settings.footContainer).Render(settings.footTmpl, data.Data.PageInfo);


                        if ($.fn.tooltip) {
                            $(this.settings.headContainer).find(tooltip).tooltip();
                            $(this.settings.footContainer).find(tooltip).tooltip();
                            this.Container.find("td a").tooltip();
                        }

                        if (settings.queryed) settings.queryed(data.Data, this);
                    }
                    else MsgBox.Error(data.Msg);
                }
            });
            return this;
        }
    }
}



